package server;

import java.io.File;
import java.io.FileNotFoundException;

import util.Logger;

import dataContracts.FileInfo;
import dataContracts.FileStatus;
import dataContracts.SharedDirectory;
import dataContracts.SharedFile;

public class ServerDirectory extends SharedDirectory {

	public ServerDirectory(String directoryPath) {
		super(directoryPath);
		
		loadFiles();
	}
	
	public void loadFiles() {
		files.clear();
		
		if (directory.isDirectory()) {
	    	for (File f : directory.listFiles()) {
	    		if (!f.isHidden())
	    			this.files.add(new SharedFile(f));
			}
    	}
		
		updateDirectoryChecksum();
	}
	
// METHODS FOR ADDING FILES TO THE COLLECTION 
	
	public void addFile(SharedFile file) {
		files.add(file);
		Logger.Debug("Added file to collection: "+ file.getName() + " ("+ files.size() +" total)");
	}
	
	public SharedFile addFile(String fileName) {
		SharedFile sf = null;
		// only add it if it's not already in there
		if (findFile(fileName) == null) {
			sf = new SharedFile(new File(fileName));
			addFile(sf);
		}
		
		return sf;
	}
	
	// this method also takes a copy of the clients local file object
	// from this we can parse out the metadata and save it 
	// TODO: move this to the SharedFile class
	public void copyMetaData(SharedFile to, SharedFile from) {
		if (to.fileState == null) {
			to.fileState = new FileInfo();
		}
		
		// copy all the metadata from the fileInfo class
		to.setName(from.getName());
		to.setComments(from.getComments());
		to.setDescription(from.getDescription());
		to.setOwner(from.getOwner());
		to.setProject(from.getProject());
		to.setTags(from.getTags());
		
		to.lastModified = from.lastModified;
		
		to.saveAttributes();
		
		Logger.Debug("Copied over metadata for "+ to.getName() + " in project "+ to.getProject());
	}
}
